import React, {Component} from 'react';
import {Button, Form, Input, Row, Col, Table, Modal, Pagination, Checkbox, DatePicker} from 'antd';
import {car} from "../value";
import app from '../AppMethod';
import {ExpressInfos,ExpressEdits} from '../components/EditComponent';
import moment from 'moment';
import {Consumer} from "../store";

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const confirm = Modal.confirm;
const RangePicker = DatePicker.RangePicker;

class ExpressManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            pagination: {
                current: 0,
                total: 0,
                pagination: 0
            },
            searchData: {},
            allPage: 0,
            data: [],
            num: '0',
        }
    };

    columns = [
        {
            title: '物流单号',
            dataIndex: 'car_no'
        },
        {
            title: '快递单号',
            dataIndex: 'car_express_num'
        },
        {
            title: '快递公司',
            dataIndex: 'car_logistics_name'
        },
        {
            title: '寄送时间',
            dataIndex: 'car_createtime'
        },
        {
            title: '最新物流状况',
            width: '400px',
            dataIndex: 'car_last_status'
        },
        {
            title: '状态',
            dataIndex: 'car_status',
            render: car_status => {
                let text;
                if (car_status == 0) {
                    text = '未配送';
                } else if (car_status == 1) {
                    text = '配送中';
                } else if (car_status == 2) {
                    text = '已完成';
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                        <ExpressInfos car_id={data.car_id}/>
                        <span style={{color: '#1890ff', cursor: 'pointer', marginLeft: '10px'}}
                              onClick={() => this.handleDetail(data.output_id)}>{'订单详情'}</span>
                        {
                            data.car_status == 1 ?
                                <span style={{color: '#1890ff', cursor: 'pointer', marginLeft: '10px'}}
                                      onClick={() => this.handleFinish(data.car_id)}>{'完成'}</span> : ''
                        }
                        <ExpressEdits data={data} handleReset={()=>this.handleAfterFinish()}/>
                    </span>
                )
            }
        }
    ];

    render() {
        return (
            <div>
                <Row>
                    <SearchLists
                        clickSearch={(value) => {
                            this.handleGetSearch(value)
                        }}
                        handleReset={() => this.handleReset()}
                    >
                    </SearchLists>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Table
                        columns={this.columns}
                        rowKey={record => record.car_no}
                        loading={this.state.loading}
                        dataSource={this.state.data}
                        pagination={false}
                    >
                    </Table>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={12} style={{fontSize: '15px'}}>
                        共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                        页
                    </Col>
                    <Col span={12} style={{textAlign: 'right'}}>
                        <Pagination {...this.state.pagination} showSizeChanger={true} showQuickJumper={true}
                                    onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}
                                    onShowSizeChange={(current, size) => this.handleSizeChange(current, size)}
                                    hideOnSinglePage={false}/>
                    </Col>
                </Row>
            </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "快递管理"});
        this.handleSearchOrderList();
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    };

    /**
     * 根据条件搜索快递单列表
     * @param value
     */
    handleGetSearch(value) {
        let times = value.car_createtime;
        let car_createtime_start = undefined;
        let car_createtime_end = undefined;
        if (times != undefined && times.length > 0) {
            car_createtime_start = moment(times[0]._d).format('YYYY-MM-DD');
            car_createtime_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let searchData = {
            car_no: value.car_no,
            output_num: value.output_num,
            customer_name: value.customer_name,
            car_status: value.car_status,
            car_createtime_start: car_createtime_start,
            car_createtime_end: car_createtime_end,
            car_express_num: value.car_express_num
        };
        this.setState({searchData});
        searchData.page = 1;
        searchData.size = this.state.pagination.pageSize || 10;
        this.handleSearchOrderList(searchData);
    };

    /**
     * 处理重置事件
     */
    handleReset() {
        this.setState({searchData: {}});
        let data = {
            page: 1,
            size: 10,
        };
        this.handleSearchOrderList(data);
    };

    /**
     * 查询快递单列表
     * @param data
     */
    handleSearchOrderList(data = {page: 1, size: 10}) {
        this.setState({loading: true});
        app.post(car.SEARCH_CARLIST3, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                let orderData = result.data.dataSet;
                for (let i = 0; i < orderData.length; i++) {
                    orderData[i].car_createtime = orderData[i].car_createtime === null ? '' : moment(orderData[i].car_createtime).format('YYYY-MM-DD HH:mm');
                }
                console.log(orderData);
                this.setState({allPage, pagination, data: orderData, loading: false});
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({allPage, pagination, data: [], loading: false});
            }
        })
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleSearchOrderList(data);
    };

    /**
     * 处理页数变化事件
     * @param current
     * @param size
     */
    handleSizeChange(current, size) {
        let data = this.state.searchData;
        data.page = current;
        data.size = size;
        this.handleSearchOrderList(data);
    };

    /**
     * 处理完成配送事件
     * @param id
     */
    handleFinish(id) {
        const _this = this;
        app.post(car.FINISH_CAR, {car_id: id}).then((result) => {
            if (result.code) {
                app.alert(result.msg, 'success', 3);
                _this.handleAfterFinish();
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 处理完成配送后搜索物流列表
     */
    handleAfterFinish() {
        let data = this.state.searchData;
        data.page = this.state.pagination.current ? this.state.pagination.current : 1;
        data.size = this.state.pagination.pageSize ? this.state.pagination.pageSize : 10;
        this.handleSearchOrderList(data);
    }

    /**
     * 跳转到订单详情页面
     * @param id
     */
    handleDetail(id) {
        this.props.history.push('/index/orderDetails/' + id);
    };
};

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const plainOptions = [
            {label: '配送中', value: '1'},
            {label: '已完成', value: '2'},
        ];
        return (
            <div>
                <Row>
                    <Form className="login-form">
                        <Row>
                            <Col span={8}>
                                <FormItem label="物流单号" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('car_no')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="订单号" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('output_num')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="客户名" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('customer_name')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>

                            <Col span={4} style={{float: 'right'}}>
                                <Button type="primary"
                                        onClick={() => this.handleSearchComplain()}
                                >
                                    查询
                                </Button>
                                <Button type="default"
                                        onClick={() => this.handleReset()}
                                        style={{marginLeft: '10px'}}
                                >
                                    重置
                                </Button>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8}>
                                <FormItem label={"创建时间"} {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('car_createtime')(
                                            <RangePicker
                                                ranges={{
                                                    Today: [moment(), moment()],
                                                    'This Month': [moment(), moment().endOf('month')]
                                                }}
                                                format={"YYYY-MM-DD"}
                                                onChange={(dates, dateStrings) => this.handleCreateTimeOnChange(dates, dateStrings)}
                                            />
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="快递单号" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('car_express_num')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label={"状态"} {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('car_status')(
                                            <CheckboxGroup options={plainOptions}
                                                           onChange={(checkedValue) => this.handleOnChange(checkedValue)}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Row>
            </div>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取搜索条件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let car_status = values.car_status;
                if (car_status != undefined && car_status.length > 0) {
                    let temp = "";
                    for (let i = 0; i < car_status.length; i++) {
                        temp += car_status[i] + ',';
                    }
                    temp = temp.substr(0, temp.length - 1);
                    values.car_status = temp;
                } else {
                    values.car_status = "";
                }
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.handleReset();
    };

    /**
     * 处理多选框变化事件
     * @param checkedValue
     */
    handleOnChange(checkedValue) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let car_status = checkedValue;
                if (car_status != undefined && car_status.length > 0) {
                    let temp = "";
                    for (let i = 0; i < car_status.length; i++) {
                        temp += car_status[i] + ',';
                    }
                    temp = temp.substr(0, temp.length - 1);
                    values.car_status = temp;
                } else {
                    values.car_status = "";
                }
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理输入框按下回车键的事件
     */
    handleOnPressEnter() {
        //调用获取搜索条件的函数
        this.handleSearchComplain();
    };

    /**
     * 处理创建时间选择框变化事件
     */
    handleCreateTimeOnChange(dates, dateStrings) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.car_createtime = dates;
                let car_status = values.car_status;
                if (car_status != undefined && car_status.length > 0) {
                    let temp = "";
                    for (let i = 0; i < car_status.length; i++) {
                        temp += car_status[i] + ',';
                    }
                    temp = temp.substr(0, temp.length - 1);
                    values.car_status = temp;
                } else {
                    values.car_status = "";
                }
                this.props.clickSearch(values);
            }
        })
    };
}

const SearchLists = Form.create()(SearchList);
const ExpressManages = Form.create()(ExpressManage);
export default prop => (
    <Consumer>
        {
            props => (
                <ExpressManages {...prop} {...props}/>
            )
        }
    </Consumer>
);